package com.wonder;

import com.wonder.excel.ExcelDealService;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 这个类不要自己写哦，使用软件sceneBuider构建
 *
 * @author jinrong.wang
 */
public class MySceneController {

    @FXML
    private Label file1Name;

    @FXML
    private Label file2Name;

    @FXML
    private Label fileDealStatus;

    @FXML
    private TextField input1;

    @FXML
    private TextField input2;

    @FXML
    private TextField input3;

    @FXML
    private TextField input4;

    @FXML
    private Button qrcode;

    @FXML
    private Button selectFile1Button;

    @FXML
    private Button selectFile1Button2;

    @FXML
    private Button submitFile;

    @FXML
    private Button submitFileDefault;

    private File file1;

    private File file2;


    @FXML
    void onInput1(ActionEvent event) {

    }

    @FXML
    void onInput2(ActionEvent event) {

    }

    @FXML
    void onInput3(ActionEvent event) {

    }

    @FXML
    void onInput4(ActionEvent event) {

    }

    @FXML
    void onSelectFile1Button(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("已选择文件 ");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("*", new String[]{"*.xlsx", "*.csv", "*.xls"})
        );
        Stage stage = (Stage) ((javafx.scene.Node) event.getSource()).getScene().getWindow();
        file1 = fileChooser.showOpenDialog(stage);
        if (file1 != null) {
            file1Name.setText(file1.getName());
        }
    }

    @FXML
    void onSelectFile2Button(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("已选择文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("*", new String[]{"*.xlsx", "*.csv", "*.xls"})
        );
        Stage stage = (Stage) ((javafx.scene.Node) event.getSource()).getScene().getWindow();
        file2 = fileChooser.showOpenDialog(stage);
        if (file2 != null) {
            file2Name.setText(file2.getName());
        }
    }

    @FXML
    void onSubmitFile(ActionEvent event) {
        try {
            fileDealStatus.setText("文件处理中.....");
            System.out.println(input1.getText());
            //校验文件是否已传
            if (file2 == null) {
                showAlert("文件校验失败", "文件1未导入", Alert.AlertType.ERROR);
                return;
            } else if (file2 == null) {
                showAlert("文件校验失败", "文件2未导入", Alert.AlertType.ERROR);
                return;
            }
            //文件比对服务
            ExcelDealService excelDealService = new ExcelDealService();
            try {
                List<String> paramLists = paramToList();
                SXSSFWorkbook workbook = null;
                try {
                    workbook = excelDealService.dealFileUploadLocalService(file1, file2, paramLists);
                } catch (Exception e) {
                    //返回前端提示
                    showAlert("文件比对失败", e.getMessage(), Alert.AlertType.ERROR);
                    return;
                }
                //处理太快，怎么让人看我炫酷的画面呢，延迟3秒，好好看
                Thread.sleep(500);
                //选择文件夹
                DirectoryChooser directoryChooser = new DirectoryChooser();
                directoryChooser.setTitle("Choose Folder");
                File directory = directoryChooser.showDialog(new Stage());
                //选择的下载路径
                String selectDownPath = "";
                if (directory != null) {
                    System.out.println(directory.getAbsolutePath());
                    selectDownPath = directory.getAbsolutePath();
                } else {
                    showAlert("下载路径", "请选择下载路径", Alert.AlertType.ERROR);
                    return;
                }
                if (selectDownPath != null && !"".equals(selectDownPath)) {
                    String downLoadPath = selectDownPath + File.separator + "比对结果." + System.currentTimeMillis() + ".xlsx";
                    //将要写入的内容写到file文件中
                    try (FileOutputStream fos = new FileOutputStream(new File(downLoadPath));) {
                        workbook.write(fos);
                    } catch (Exception e) {
                        showAlert("文件下载失败", e.getMessage(), Alert.AlertType.ERROR);
                        return;
                    }
//                    showAlert("文件下载完成,文件路径", downLoadPath, Alert.AlertType.CONFIRMATION);
                    fileDealStatus.setText("文件处理完成，保存至" + downLoadPath);

                    //////////// 图片弹窗
//                    Image image = new Image(getClass().getResourceAsStream("/qrcode.png"));
//                    Stage popupState = new Stage();
//                    ImageView imageView = new ImageView(image);
//                    StackPane root = new StackPane(imageView);
//                    popupState.setScene(new Scene(root));
//                    popupState.setTitle("文件存放路径：" + downLoadPath);
//                    popupState.show();

                }
            } catch (Exception e) {
                showAlert("文件比对失败", e.getMessage(), Alert.AlertType.ERROR);
            }
        } catch (Exception e) {
            System.out.println("嗯嗯");
        } finally {
        }
    }
    @FXML
    void onSubmitFileDefault(ActionEvent event) {
        try {
            fileDealStatus.setText("文件处理中.....");
            System.out.println(input1.getText());
            //校验文件是否已传
            if (file2 == null) {
                showAlert("文件校验失败", "文件1未导入", Alert.AlertType.ERROR);
                return;
            } else if (file2 == null) {
                showAlert("文件校验失败", "文件2未导入", Alert.AlertType.ERROR);
                return;
            }
            //文件比对服务
            ExcelDealService excelDealService = new ExcelDealService();
            try {
                List<String> paramLists = paramToList();
                SXSSFWorkbook workbook = null;
                try {
                    workbook = excelDealService.dealFileUploadLocalService(file1, file2, paramLists);
                } catch (Exception e) {
                    //返回前端提示
                    showAlert("文件比对失败", e.getMessage(), Alert.AlertType.ERROR);
                    return;
                }
                //用户目录
                String userHome = System.getProperty("user.home");
                //下载目录
                String downloadPath = userHome;
                //判断文件夹是否存在
                File f = new File(userHome + File.separator + "Downloads");
                if (f.exists() && f.isDirectory()) {
                    downloadPath = f.getAbsolutePath();
                }
                //写入文件
                if (downloadPath != null && !"".equals(downloadPath)) {
                    String downLoadPath = downloadPath + File.separator + "比对结果." + System.currentTimeMillis() + ".xlsx";
                    //将要写入的内容写到file文件中
                    try (FileOutputStream fos = new FileOutputStream(new File(downLoadPath));) {
                        workbook.write(fos);
                    } catch (Exception e) {
                        showAlert("文件下载失败", e.getMessage(), Alert.AlertType.ERROR);
                        return;
                    }
                    fileDealStatus.setText("文件处理完成，保存至" + downLoadPath);
                }
            } catch (Exception e) {
                showAlert("文件比对失败", e.getMessage(), Alert.AlertType.ERROR);
            }
        } catch (Exception e) {
            System.out.println("嗯嗯");
        } finally {

        }
    }

    @FXML
    void onQrcode(ActionEvent event) {
        //////////// 图片弹窗
        Image image = new Image(getClass().getResourceAsStream("/qrcode.png"));
        Image excelImage = new Image(getClass().getResourceAsStream("/excel.png"));
        Stage popupState = new Stage();
        ImageView imageView = new ImageView(image);
        StackPane root = new StackPane(imageView);
        popupState.setScene(new Scene(root));
        popupState.setTitle("谢谢");
        popupState.getIcons().add(excelImage);
        popupState.show();
    }
    private void showAlert(String title, String content, Alert.AlertType alertType) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public List<String> paramToList() {
        List<String> nameParams = new ArrayList<String>();
        if (null != input1.getText() && !"".equals(input1.getText())) {
            nameParams.add(input1.getText());
        }
        if (null != input2.getText() && !"".equals(input2.getText())) {
            nameParams.add(input2.getText());
        }
        if (null != input3.getText() && !"".equals(input3.getText())) {
            nameParams.add(input3.getText());
        }
        if (null != input4.getText() && !"".equals(input4.getText())) {
            nameParams.add(input4.getText());
        }
        return nameParams;
    }


}
